package com.yigo.cuc.app.service;

import com.yigo.cuc.api.constant.CusCodeEnum;
import com.yigo.cuc.api.customer.command.CustomerRegisterCmd;
import com.yigo.cuc.api.customer.command.UpdateNickNameCmd;
import com.yigo.cuc.api.customer.resp.CustomerRegisterResp;
import com.yigo.cuc.app.assembler.CustomerDTO2DmoAssembler;
import com.yigo.cuc.domain.customer.aggregateroot.Customer;
import com.yigo.cuc.domain.customer.repo.CustomerRepo;
import com.yigo.framework.http.BException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author chenzl
 */
@Slf4j
@Service
public class CustomerAppService {
    @Resource
    private CustomerRepo customerRepo;

    /**
     * 注册
     *
     * @param cmd
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public CustomerRegisterResp register(CustomerRegisterCmd cmd) {
        Long count = customerRepo.countByUserNameOrEmailOrPhone(cmd.getUserName(), cmd.getEmail(), cmd.getPhone());
        if (count > 0) {
            throw new BException(CusCodeEnum.REGISTER_USER_EXISTS, cmd.getUserName(), cmd.getEmail(), cmd.getPhone());
        }
        Customer customer = CustomerDTO2DmoAssembler.INSTANCE.toDmo(cmd);
        customerRepo.save(customer);
        return CustomerDTO2DmoAssembler.INSTANCE.toRegisterResp(customer);
    }

    @Transactional(rollbackFor = Exception.class)
    public Long updateNickName(UpdateNickNameCmd cmd) {
        Customer customer = customerRepo.findById(cmd.getId());
        customer.setNickName(cmd.getNickName());
        customerRepo.save(customer);
        return customer.getId();
    }
}
